package com.mallcai.bigdata.ladon.service.peekdata.impl;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.common.SessionThreadLocal;
import com.mallcai.bigdata.ladon.dpl.entity.peekdata.ImportRecord;
import com.mallcai.bigdata.ladon.dpl.mapper.peekdata.ImportRecordMapper;
import com.mallcai.bigdata.ladon.dpl.vo.ImportStatusType;
import com.mallcai.bigdata.ladon.service.peekdata.IImportRecordService;
import com.mallcai.bigdata.ladon.service.system.IAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-12 16:30
 */
@Service
@Slf4j
public class ImportRecordService implements IImportRecordService {

    @Autowired
    private ImportRecordMapper importRecordMapper;

    @Autowired
    private IAccountService iAccountService;

    @Transactional
    @Override
    public int add(ImportRecord record) {
        int status =  importRecordMapper.insert(record);

        if (status == 0){
            throw new BusinessException("增加导入记录失败");
        }
        return status;
    }

    @Override
    public List<ImportRecord> getByParams(Map<String, Object> params) {
        if (!iAccountService.isSuperMan()){
            params.put("createdBy", SessionThreadLocal.getUserId());
        }
        return importRecordMapper.getByParams(params);
    }


    private int updateStatus(Long id, ImportStatusType status, String errorInfo) {
        return importRecordMapper.updateStatus(id, status.getCode(), errorInfo);
    }

    @Override
    public void fail(Long id, String errorInfo) {
        updateStatus(id, ImportStatusType.FAILED, errorInfo);
    }

    @Override
    public void success(Long id) {
        updateStatus(id, ImportStatusType.SUCCESS, "");
    }
}
